package cmd

import (
	"fmt"
	"github.com/gchaincl/dotsql"
	"github.com/spf13/cobra"
	"github.com/xwb1989/sqlparser"
)

var parse = &cobra.Command{
	Use:   "check",
	Short: "Check sql",
	Long:  `migration parse <sql file>`,
	Args:  cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		dot, err := dotsql.LoadFromFile(args[0])
		if err != nil {
			fmt.Println("loadfromfile failed", err)
			return
		}

		m := dot.QueryMap()

		for _, v := range m {
			_, err = IsSQLValid(v)
			if err != nil {
				fmt.Println("SQL valid failed", err)
			}
		}
	},
}

func init() {
	rootCmd.AddCommand(parse)
}

func IsSQLValid(sql string) (bool, error) {
	_, err := sqlparser.Parse(sql)
	if err != nil {
		return false, err
	}
	return true, nil
}
